#!/usr/bin/perl
#	IPS/IDS database maintnance
#	Usage:
#
#	sdee-dbm.pl [/path/to/config.file]
#
#       Default config file - /usr/local/etc/sdee.conf
#
#(c) 2008 Alexander Klepikov klepikov.alex@gmail.com

use DBI;
use Config::General;

#Declare global vars and defaults
#Database host
my $dbhost="sql.your.domain.com";
#Database driver - see man DBI
my $dbdriver="Pg";
#Database name
my $dbname="sdee";
#Database table
my $dbtable="sdee";
#Database user and password
my $username="pgsql";
my $password="";
#How long we should keep history
my $dbhistory="1 year";
#SQL cleanup query
#Default for PostgreSQL
my $sql = "delete from $dbtable where time < date_trunc('day', now()) - interval '$dbhistory'";
#Default config file
my $config_file = "/usr/local/etc/sdee.conf";
#Get config file from command line
if (@ARGV >= 1)
{
  $config_file = $ARGV[0];
}

#Read config
$conf = new Config::General( -ConfigFile     => $config_file,
           -ExtendedAccess => 1,
	   -InterPolateVars => 1);
my %config = $conf->getall;

$dbhost = %config->{ dbhost } if $conf->exists('dbhost');
$dbdriver = %config->{ dbdriver } if $conf->exists('dbdriver');
$dbname = %config->{ dbname } if $conf->exists('dbname');
$dbtable = %config->{ dbtable } if $conf->exists('dbtable');
$dbusername = %config->{ dbusername } if $conf->exists('dbusername');
$dbpassword = %config->{ dbpassword } if $conf->exists('dbpassword');
$dbhistory = %config->{ dbhistory } if $conf->exists('dbhistory');
$sql = %config->{ dbclean } if $conf->exists('dbclean');

#Connect to database
$dbh = DBI->connect("dbi:$dbdriver:dbname=$dbname;host=$dbhost","$dbusername","$dbpassword",
                                {PrintError => 0});

#Report errors
if ($DBI::err != 0) {
	print $DBI::errstr . "\n";
	exit($DBI::err);
}

#Print SQL query
#print "$sql\n";
#Execute SQL query
my $rv = $dbh->do($sql);

#Report errors
if (!defined $rv) {
     print "Error executing query '$sql': ".$dbh->errstr."\n";
}

#Do cleanup
$dbh->disconnect();
